import sys
import Weather
from PyQt5.QtWidgets import QApplication, QDialog
import requests


class MainDialog(QDialog):
    def __init__(self, parent=None):
        super(QDialog, self).__init__(parent)
        self.ui = Weather.Ui_Dialog()
        self.ui.setupUi(self)

    def queryWeather(self):
        cityName = self.ui.comboBox.currentText()
        cityCode = self.getCode(cityName)
        print(cityName)
        r = requests.get("http://www.weather.com.cn/data/cityinfo/{}.html".format(cityCode))
        r.encoding = 'utf-8'
        if r.json():
            weatherMsg = '城市：{}\n天气：{}\n温度：{}-{}\n'.format(
                r.json()['weatherinfo']['city'],
                r.json()['weatherinfo']['weather'],
                r.json()['weatherinfo']['temp1'],
                r.json()['weatherinfo']['temp2'],

            )
        else:
            weatherMsg = '天气查询失败，请稍后再试！'

        self.ui.textEdit.setText(weatherMsg)

    def getCode(self, cityName):
        cityDict = {"北京": "101010100",
                    "上海": "101020100",
                    "天津": "101030100"}

        return cityDict.get(cityName, '101010100')

    def clearText(self):
        self.ui.textEdit.clear()


if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    myDlg = MainDialog()
    myDlg.show()
    sys.exit(myapp.exec_())